package com.h3c.ptability.controller;

import cn.hutool.json.JSONUtil;
import com.h3c.ptability.bo.ElectronicSignBO;
import com.h3c.ptability.bo.GetSfsIdsBO;
import com.h3c.ptability.config.SpringUtil;
import com.h3c.ptability.dto.electronicSign.callback.CallbackDTO;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IElectronicSignService;
import com.h3c.ptability.support.ResultData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;


/**
 * @author chenyifan
 * @date 2022/5/16 10:21
 * 电子签名接口
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/electronic")
public class ElectronicSignController {

    private final IElectronicSignService electronicSignService;

    private static final String FINISH_ACTION = "SIGN_FLOW_FINISH";

    private static final String UPDATE_ACTION = "SIGN_FLOW_UPDATE";

    private static final Integer SUCCESS_STATUS = 2;

    private static final Integer REJECT_STATUS = 7;

    /**
     * 电子签名
     *
     * @param electronicSignBO 服务间请求流转bo
     * @return 签名地址
     */
    @PostMapping("/signPdfFile")
    public ResultData<String> signFile(@RequestBody ElectronicSignBO electronicSignBO) {
        try {
            String failWorkerIds = electronicSignService.finalSignFile(electronicSignBO, false);
            if (StringUtils.hasText(failWorkerIds)) {
                return ResultData.success("员工工号为:{}的电子签章提交失败，原因:{}，其余电子签章流程提交成功", failWorkerIds, "场景存在异常记录");
            }
            return ResultData.success("电子签章流程提交成功");
        } catch (Exception e) {
            log.error("电子签名失败:{}", e.getMessage());
            return ResultData.fail("电子签名失败:{}", e.getMessage());
        }
    }

    /**
     * 经过检查启动公司签章
     * @param recordIds
     * @return
     */
    @PostMapping("/checkAndSignOrg")
    public ResultData<String> checkAndSignOrg(@RequestBody List<String> recordIds) {
        try {
            electronicSignService.checkAndSignOrg(recordIds);
            return ResultData.success("公司签章提交成功");
        } catch (Exception e) {
            log.error("公司签章提交失败:{}", e.getMessage());
            return ResultData.fail("公司签章提交失败:{}", e.getMessage());
        }
    }

    /**
     * 导入excel进行电子签名
     *
     * @param file
     * @param sceneType
     * @param appId
     * @return
     */
    @PostMapping("/excelSignPdfFile")
    public ResultData<String> excelSignPdfFile(@RequestParam("file") MultipartFile file,
                                               @RequestParam("file") String templateCode,
                                               @RequestParam("sceneType") Integer sceneType,
                                               @RequestParam("appId") String appId) {
        try {
            String parseResult = SpringUtil.getBean(CommService.class).parseExcelByTemplate(templateCode, file);
            HashMap<String, String> param = new HashMap<>(1);
            param.put(ElectronicSignBO.USER_INFO_LIST, parseResult);
            ElectronicSignBO electronicSignBO = new ElectronicSignBO();
            electronicSignBO.setUserData(JSONUtil.parseObj(JSONUtil.toJsonStr(param)));
            electronicSignBO.setAppId(appId);
            electronicSignBO.setSceneType(sceneType);
            String failWorkerIds = electronicSignService.finalSignFile(electronicSignBO, false);
            if (StringUtils.hasText(failWorkerIds)) {
                return ResultData.success("员工工号为:{}的电子签章提交失败，原因:{}，其余电子签章流程提交成功", failWorkerIds, "场景存在异常记录");
            }
            return ResultData.success("电子签章流程提交成功");
        } catch (Exception e) {
            log.error("电子签名失败:{}", e.getMessage());
            return ResultData.fail("电子签名失败:{}", e.getMessage());
        }
    }


    /**
     * 重新签署
     *
     * @param electronicSignBO 服务间请求流转bo
     * @return 签名地址
     */
    @PostMapping("/reSignFile")
    public ResultData<String> reSignFile(@RequestBody ElectronicSignBO electronicSignBO) {
        try {
            electronicSignService.reSignFile(electronicSignBO);
            return ResultData.success("电子签章流程提交成功");
        } catch (Exception e) {
            log.error("电子签名失败:{}", e.getMessage());
            return ResultData.fail("电子签名失败:{}", e.getMessage());
        }
    }


    /**
     * 取消签署流程
     *
     * @param recordId
     * @param reason
     * @return
     */
    @GetMapping("/cancelSignRecord")
    public ResultData<String> cancelSignRecord(@RequestParam String recordId,
                                               @RequestParam String reason) {
        try {
            electronicSignService.cancelSignRecord(recordId, reason);
            return ResultData.success("取消签署流程成功");
        } catch (Exception e) {
            log.error("取消签署流程失败:{}", e.getMessage());
            return ResultData.fail("取消签署流程失败:{}", e.getMessage());
        }
    }

    /**
     * e签报催办签署
     *
     * @param recordId 记录id
     * @return
     */
    @GetMapping("/remindSign")
    public ResultData<String> remindSign(@RequestParam String recordId) {
        try {
            electronicSignService.remindSignRecord(recordId);
            return ResultData.success("e签报催办签署成功");
        } catch (Exception e) {
            log.error("e签报催办签署失败:{}", e.getMessage());
            return ResultData.fail("e签报催办签署失败:{}", e.getMessage());
        }
    }

    /**
     * 获取附件id
     * @param getSfsIdsBO
     * @return
     */
    @PostMapping("/getSignSfsIds")
    public ResultData<List<String>> getSignSfsIds(@RequestBody GetSfsIdsBO getSfsIdsBO) {
        try {
            return ResultData.data(electronicSignService.getSignSfsIds(getSfsIdsBO));
        } catch (Exception e) {
            log.error("e签报催办签署失败:{}", e.getMessage());
            return ResultData.fail("e签报催办签署失败:{}", e.getMessage());
        }
    }


    /**
     * 个人电子签名回调
     *
     * @param callbackDTO 回调DTO
     */
    @PostMapping("/callback")
    public void callback(@RequestBody CallbackDTO callbackDTO) {
        log.info("回调返回值:{}", JSONUtil.toJsonStr(callbackDTO));
        if (org.apache.commons.lang3.StringUtils.equals(FINISH_ACTION, callbackDTO.getAction())) {
            if (Objects.nonNull(callbackDTO.getStatus()) && callbackDTO.getStatus().equals(SUCCESS_STATUS)) {
                try {
                    electronicSignService.callbackFinish2(callbackDTO);
                } catch (Exception e) {
                    log.error("回调发生错误:{}", e.getMessage());
                }
            } else if (Objects.nonNull(callbackDTO.getStatus()) && callbackDTO.getStatus().equals(REJECT_STATUS)) {
                try {
                    electronicSignService.callbackReject(callbackDTO);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else if(org.apache.commons.lang3.StringUtils.equals(UPDATE_ACTION, callbackDTO.getAction())){
            if(Objects.nonNull(callbackDTO.getStatus()) && callbackDTO.getStatus().equals(SUCCESS_STATUS)){
                try {
                    electronicSignService.updateProcess(callbackDTO);
                } catch (Exception e) {
                    log.error("回调发生错误:{}", e.getMessage());
                }
            }
        }
    }
}
